package org.cancerregulome.redi.websvc.model;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.util.Map;
import java.util.logging.Logger;

import static org.apache.commons.lang.StringUtils.equalsIgnoreCase;

/**
 * @author hrovira
 */
public class DatasetModelAlterationListener implements FileAlterationListener {
    private static final Logger log = Logger.getLogger(DatasetModelAlterationListener.class.getName());

    private final File rootPath;
    private final Map<String, DatasetModel> datasetModels;

    public DatasetModelAlterationListener(File rootPath, Map<String, DatasetModel> models) {
        this.rootPath = rootPath;
        this.datasetModels = models;
        this.loadDatasets();
    }

    protected void loadDatasets() {
        this.datasetModels.clear();

        File rediConfig = new File(this.rootPath, "redi.config");
        File[] fs = this.rootPath.listFiles();
        if (fs != null) {
            for (File mf : fs) {
                if (mf.isDirectory()) {
                    try {
                        DatasetModel dm = new DatasetModel(mf, rediConfig);
                        this.datasetModels.put(dm.ID(), dm);
                    } catch (Exception e) {
                        log.warning(e.getMessage());
                    }
                }
            }
        }
    }

    public void onStart(FileAlterationObserver observer) {
    }

    public void onStop(FileAlterationObserver observer) {
    }

    public void onDirectoryCreate(File file) {
        log.info("dir_create=" + file);
        this.loadDatasets();
    }

    public void onDirectoryChange(File file) {
        log.info("dir_change=" + file);
        this.loadDatasets();
    }

    public void onDirectoryDelete(File file) {
        log.info("dir_delete=" + file);
        this.loadDatasets();
    }

    public void onFileCreate(File file) {
        log.info("create=" + file);
        this.loadDatasets();
    }

    public void onFileChange(File file) {
        log.info("change=" + file + ": only loading if dataset.json");
        if (equalsIgnoreCase(file.getName(), "dataset.json")) {
            this.loadDatasets();
        }
    }

    public void onFileDelete(File file) {
    }
}
